<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>css吸附效果</title>
    <style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      .container {
        width: 100%;
        height: 100vh;
        background-image: url("data:image/svg+xml;charset=utf-8,%3Csvg\ width='20'\ height='20'\ xmlns='http://www.w3.org/2000/svg'%3E%3Cg\ fill-opacity='.05'\ fill-rule='evenodd'%3E%3Ccircle\ cx='3'\ cy='3'\ r='3'/%3E%3Ccircle\ cx='13'\ cy='13'\ r='3'/%3E%3C/g%3E%3C/svg%3E");
        background-size: 3%;
        background-color: rgba(0, 0, 0, 0.8);
        overflow-x: auto;
        display: flex;
        flex-wrap: nowrap;
        /* 设置水平滚动的吸附点 */
        scroll-snap-type: x mandatory;
      }

      .item {
        width: 100%;
        height: 100%;
        flex-shrink: 0;
        /* 吸附在父元素的中心位置 */
        scroll-snap-align: center;
        /* 子元素滚动停止位置一定会停在滚动吸附点 */
        scroll-snap-stop: always;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .img {
        width: 60vw;
        height: 82.8vw;
      }

      #float {
        animation: float infinite 5s ease;
      }

      @keyframes float {
        0% {
          transform: translateY(0);
        }
        50% {
          transform: translateY(-10%) scale(1.05);
        }
        100% {
          transform: translateY(0);
        }
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="item">
        <img class="img" src="./imgs/1.png" alt="" />
      </div>
      <div class="item">
        <img class="img" src="./imgs/2.png" alt="" />
      </div>
      <div class="item">
        <img class="img" src="./imgs/3.png" alt="" />
      </div>
      <div class="item">
        <img class="img" src="./imgs/4.png" alt="" />
      </div>
      <div class="item">
        <img class="img" src="./imgs/5.png" alt="" />
      </div>
      <div class="item">
        <img class="img" src="./imgs/6.png" alt="" />
      </div>
    </div>
  </body>

  <script>
    document.addEventListener("DOMContentLoaded", function () {
      const imgs = document.querySelectorAll(".img");

      const observer = new IntersectionObserver(
        (entries) => {
          entries.forEach((entry) => {
            if (entry.isIntersecting) {
              entry.target.id = "float";
            } else {
              entry.target.removeAttribute("id");
            }
          });
        },
        {
          root: null, // 使用视口作为根
          rootMargin: "0px",
          threshold: 0.1, // 当至少 10% 的目标元素可见时触发回调
        }
      );

      imgs.forEach((e) => {
        observer.observe(e);
      });
    });
  </script>
</html>
